   package com.javalong.affairs.base.data;

import java.util.List;

import android.util.SparseArray;

import com.javalong.affairs.base.exception.DataNoExistException;
import com.javalong.affairs.base.exception.TypeNoMatchExpcetion;

/**
 * 用来存储所有的的 数据
 */
public class AllData {
	private SparseArray<Object> allData;
	private static AllData self;

	private AllData() {
		allData = new SparseArray<Object>();
	}

	public static AllData GetInstance() {
		if (self == null) {
			self = new AllData();
		}
		return self;
	}

	public synchronized void registerData(int resId, Object obj) {
		if (allData.indexOfKey(resId) < 0) {
			allData.append(resId, obj);
		}
	}

	public synchronized void forceRegisterData(int resId, Object obj) {
		if (allData.indexOfKey(resId) >= 0) {
			allData.remove(resId);
		}
		allData.append(resId, obj);
	}

	public synchronized void unRegisterData(int resId) {
		if (allData.indexOfKey(resId) >= 0) {
			allData.remove(resId);
		} else {
			throw new DataNoExistException("数据不存在");
		}
	}

	public Object get(int resId) {
		if (allData.indexOfKey(resId) >= 0) {
			return allData.get(resId);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public <E> List<E> appendListData(int resId, List<E> list) {
		if (allData.indexOfKey(resId) >= 0) {
			Object obj = allData.get(resId);
			if (obj instanceof List) {
				List<E> data = (List<E>) obj;
				if (list != null) {
					data.addAll(list);
				}
				return data;
			} else {
				throw new TypeNoMatchExpcetion("数据类型不匹配！");
			}
		} else {
			allData.append(resId, list);
			return list;
		}
	}

	@SuppressWarnings("rawtypes")
	public void clearList(int resId) {
		if (allData.indexOfKey(resId) >= 0) {
			Object obj = allData.get(resId);
			if (obj instanceof List) {
				List list = (List) obj;
				list.clear();
			}
		}
	}
}
